home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: ?? How to dump text files to screen ??
- Date: 15 Mar 1996 22:24:34 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4idmr2INNol@keats.ugrad.cs.ubc.ca>
- References: <31430CE8.469E@aol2.com> <4iddva$aic@sue.cc.uregina.ca>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <4iddva$aic@sue.cc.uregina.ca>,
- Tristan Psionic <tristan@nether.net> wrote:
- >In <31430CE8.469E@aol2.com>, Neil <neil@aol2.com> writes:
- >>I need help -- how can I open up a text file and just dump it
- >>all out (in plain text) to the screen?
- >Well, you can't do exactly that, but this is pretty close (and pretty raw):
- >
- >#include <stdio.h>
- >
- >void main (int argc,char argv[])
- >{
- > FILE *fp;
- > char s[1000];
- > if (argc >= 1)
- > {
- > fp=fopen(argv[1],"r");
- > while (gets(s,1000,fp) != NULL)
- > {
- > printf("%s",s);
- > }
- > fclose(fp);
- > }
- > else
- > {
- > printf("usage: dumptext [filename]"
- > }
- >}
- >
- >That should work. I'm not an expert at C or anything, but I do believe that
- >there aren't any hugely flawed errors in it. Good luck.
-
- Good luck with correctly reproducing lines over 1000 characters.
-
- Wrong return value from main(). Should be int.
-
- No exit status. Unbalanced parenthesis in printf().
-
- Tries to use argv[1] even if argc is merely equal to 1.
-
- Never checks whether fopen() returns NULL.
-
- A NULL return from fgets() could indicate an end of file _or_ an error.
-
- gets() is written mistakenly instead of fgets().
-
-
- No HUGELY flawed errors, though. Nope. :)
-
- #include <stdio.h>
- #include <errno.h>
- #include <stdlib.h>
-
- /*
- * a useless form of 'cat'
- */
-
- int main(int argc, char *argv[])
-
- {
- FILE *input;
- char **arg, c;
-
- if (argc > 1) { /* file arguments available */
- for (arg = argv + 1; arg < argv + argc; arg++) {
- input = fopen(*arg,"r");
- if (!input) {
- perror(*arg);
- exit(EXIT_FAILURE);
- }
- while ((c = getc(input)) != EOF)
- if (putc(c, stdout) == EOF)
- break;
- if (ferror(input)) {
- perror(*arg);
- exit(EXIT_FAILURE);
- }
- if (ferror(stdout)) {
- perror("standard output");
- exit(EXIT_FAILURE);
- }
- fclose(input);
- }
- } else { /* no arguments given */
- fprintf(stderr,"usage: %s [ file1 ] [ file2 ] ...\n",
- argv[0] ? argv[0] : "<command_name>");
- }
- return 0;
- }
-
- I actually tested that, unlike you, with all the diagnostics the compiler can
- muster enabled. No room for cockiness on comp.lang.c.
-
- There is no need to use a buffer. The putc() and getc() functions are often
- defined as macros which operate directly and efficiently on the FILE structure,
- calling for buffer flushes and replenishes as needed. The while() loop above is
- probably more efficient than fgets(), and doesn't require extra buffering.
- --
-
-